package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.CuccServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.util.ProductFeeInstUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Objects;

/**
 * 止租时间
 * Created by chencheng110 on 2021/03/12 20:40
 */
@Service
public class RentStopTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        if(KiteStringUtils.isNotEmpty(commonAttr.getValue())){
            return;
        }
        String postProvinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANGHAI, postProvinceNbr)) {
            // 上海 停机、预销户/销户时的止租：默认“自动止租”，止租时间以页面录入的止租时间为准，可修改
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            String nowdate = df.format(calendar.getTime());

          /*  commonAttr.setValue(nowdate);
            commonAttr.setValueDesc(nowdate);*/
            commonAttr.setDefaultValue(nowdate);
            setCommonAttr(commonAttr);
        } else {
            // 湖南选择自动止租时，“止租时间”展示，允许手动输入选择，“手动止租”不展示止租时间
            if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_HUNAN, postProvinceNbr)) {
                KiteAttr stopRentAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.STOP_RENT_WAY);
                if (Objects.nonNull(stopRentAttr)) {
                    if (KiteStringUtils.equals(stopRentAttr.getValue(), "1")) {
                        commonAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_E);
                    } else {
                        commonAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                    }
                }
            }
            // 默认当月最后一秒
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar ca = Calendar.getInstance();
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String lastDay = format.format(ca.getTime());
            String completeTime = lastDay + " 23:59:59";
            commonAttr.setValue(completeTime);
            commonAttr.setValueDesc(completeTime);
            setCommonAttr(commonAttr);
        }
    }


    /**
     * 五大双线 止租时间不能小于上个月月底最后一天
     * @author zhang.song
     * @date 2021-05-14 10:45
     */
    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        if(KiteStringUtils.isNotEmpty(value) && value.length() > 9) {
            String catagoryId = CuccPosServiceUtils.getCateId(sceneInstId, KiteWebContext.getContext().getCustId());
            // 是否五大双线
            if(KiteStringUtils.equalsAny(catagoryId, ProdCateUtil.getDoubleLineCateIdForArr())) {
                String serviceOfferId = querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
                //不校验止租时间的情况
                String serviceOfferIdListStr = DcPublicCache.getPCode("20210804095201", "RentStopTimeCheck");
                if (!KiteStringUtils.equalsAny(serviceOfferId, serviceOfferIdListStr.split(SymbolConsts.COMMA))) {
                    String selectValue = value.substring(0, 10);
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateFormatUtils.DATE_FORMAT);
                    LocalDate localDate = null;
                    try {
                        localDate = LocalDate.parse(selectValue, dtf);
                    } catch (Exception e) {
                        ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
                    }

                    if(localDate != null) {
                        // 上个月月末最后一天
                        LocalDate minLocalDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).plusDays(-1);
                        if(localDate.isBefore(minLocalDate)) {
                            BssException.throwOut("", "", "止租时间不能小于上个月月底最后一天");
                        }
                    }
                }

            }
        }
        super.apply(sceneInstId, fieldName, value, valueDesc);
        //预销户处理趸交资费的失效时间
//        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
//        if (KiteStringUtils.isEqual(CuccServiceOfferConsts.SERVICE_OFFER_ACCOUNT_CANCEL, sceneInst.getServiceOfferId())) {
//            ProductFeeInstUtils.dealOneOffFeeExpireTime(sceneInstId);
//        }
        return ErrorConsts.SUCCESS.getResult(true);
    }
}
